package com.zhangdi.dwcache.ehcache;

import com.zhangdi.dwtools.io.ResourceUtils;
import net.sf.ehcache.CacheManager;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhangdi on 2020/08/14 11:54:48.
 */

@Configuration
public class EhCacheConfig {
    @Bean
    public CacheManager cacheManager() {
        CacheManager cacheManager = CacheManager.getCacheManager("dwcache");
        if (null == cacheManager) {
            return new CacheManager(getCacheManagerConfigFileInputStream());
        } else {
            return cacheManager;
        }
    }

    /**
     * 返回配置文件流 避免ehcache配置文件一直被占用，无法完全销毁项目重新部署
     */
    private InputStream getCacheManagerConfigFileInputStream() {
        String configFile = "classpath:ehcache.xml";
        InputStream inputStream = null;
        InputStream in = null;
        try {
            inputStream = ResourceUtils.getInputStreamForPath(configFile);
            byte[] b = IOUtils.toByteArray(inputStream);
            in = new ByteArrayInputStream(b);
            return in;
        } catch (IOException e) {
            throw new RuntimeException("Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]");
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
